﻿using System.Collections.Generic;
using System.IO;
using System.Web.Hosting;
using System.Web.Routing;
using Freedom.Framework.Mvc.Module;

namespace Freedom.Framework.Mvc
{
    public class Utils
    {
        private const string ModuleRootPath = "~/Modules";
        private static readonly IList<ModuleInfo> Modules = new List<ModuleInfo>();

        public static string GetAreaName(RouteData routeData)
        {
            object module;
            routeData.Values.TryGetValue("Area", out module);
            return module == null? string.Empty: module.ToString();
        }

        public static IEnumerable<ModuleInfo> GetModuleInfo()
        {
            //load the modules
            if (Modules.Count == 0)
            {
                var modulesRootFolder = HostingEnvironment.MapPath(ModuleRootPath);
                if (modulesRootFolder != null)
                {
                    foreach (var singleModuleFolder in Directory.GetDirectories(modulesRootFolder))
                    {
                        var tempModuleDirectory = new DirectoryInfo(singleModuleFolder);
                        var tempAssemblyName = string.Format("{0}.dll", new DirectoryInfo(singleModuleFolder).Name);
                        var tempAssemblyFilesPath = Directory.GetFiles(Path.Combine(singleModuleFolder, "bin"), tempAssemblyName, SearchOption.AllDirectories);

                        Modules.Add(
                            new ModuleInfo
                                {
                                   ModuleDirectory = tempModuleDirectory,
                                   Name = tempModuleDirectory.Name,
                                   ModuleDirectoryPath = tempModuleDirectory.FullName,
                                   AssemblyFilePath = tempAssemblyFilesPath.Length > 0? tempAssemblyFilesPath[0] : string.Empty
                                });
                    }
                }
            }
            return Modules;
        }
    }
}
